import { Request } from "./request"
import { AuthRequest, TokenResponse } from "./Type/Token"
import { MessageResultResponse, MessageResultResponseErr, postDevicesMessageRequest } from "./Type/DevicesMessage"
import { DeviceShadowResponse } from "./Type/DeviceShadow"
import { DeviceListResponse } from "./Type/DevicesList"
import { EndPointAlarmHistoryResponse, EndPointAlarmResponse, EndPointAlarmStatisticsResponse } from "./Type/EndPoint"
import { ChatCompletion } from "./Type/AI"
import { DeviceShadowManagerInstance } from "../model/devicesInfo"
import Fetch from "@system.fetch"
import { http } from "@kit.NetworkKit"

// ====================== Token ======================

export const getToken = async () => {
  const axios = new Request('https://iam.cn-north-4.myhuaweicloud.com', {
    isToken:false
  })

  const str: AuthRequest = {
    "auth": {
      "identity": {
        "methods": ["password"],
        "password": { "user": { "name": "car", "password": "123456mc", "domain": { "name": "zjh6014" } } }
      },
      "scope": { "project": { "name": "cn-east-3" } }
    }
  }

  return await axios.post<TokenResponse>('/v3/auth/tokens', str)
}


// ====================== 设备 ======================

const axios = new Request('https://7acc11ea0d.st1.iotda-app.cn-north-4.myhuaweicloud.com')

/**
 * 获取产品列表
 */
// export const getProductsList = (projectID: string) => axios.get<>(`/v5/iot/${projectID}/products`)

/**
 * 获取设备列表
 */
export function getDevicesList(projectID: string) {
  console.log("获取设备列表")
  return axios.get<DeviceListResponse>(`/v5/iot/${projectID}/devices`)
}

/**
 * 获取设备影子数据
 */
export function getDeviceShadow(project_id: string, device_id: string) {
  console.log("<请求>获取设备影子数据")
  return axios.get<DeviceShadowResponse>(`/v5/iot/${project_id}/devices/${device_id}/shadow`)
}

/**
 * 下发设备消息
 */
export function sendDevicesMessage(project_id: string, device_id: string, data: postDevicesMessageRequest) {
  console.log("<请求>下发设备消息")
  return axios.post<MessageResultResponse | MessageResultResponseErr>(`/v5/iot/${project_id}/devices/${device_id}/messages`, data)
}


// ====================== 后端数据搜集相关 ======================

const EndPoint = new Request('http://122.51.25.139:8130', { isToken: false })

/**
 * 触发车门异常打开报警上传
 * @returns
 */
export function triggerDoorOpenAlarm() {
  return EndPoint.post<EndPointAlarmResponse>("/api/alarm/door-open")
}

/**
 * 触发车门异常震动报警上传
 * @returns
 */
export function triggerDoorVibrationAlarm() {
  return EndPoint.post<EndPointAlarmResponse>("/api/alarm/door-vibration")
}

/**
 * 获取报警统计
 * @returns
 */
export function getAlarmStatistics() {
  return EndPoint.get<EndPointAlarmStatisticsResponse>("/api/alarm/statistics")
}

/**
 * 获取报警统计
 * @returns
 */
export function getAlarmHistory() {
  return EndPoint.get<EndPointAlarmHistoryResponse>("/api/alarm/history?limit=20")
}


// ====================== AI相关 ======================
interface AIRequestData {
  model: string;
  messages: object[];
  max_tokens?: number
}

export async function sendAiChat(msg:string): Promise<string> {
  // 先行判断是否是关键字
  const triggerKeywords = ['查询设备状态', '设备状态', '设备情况', '设备怎么样', '设备运行'];
  let mymsg = msg
  if (triggerKeywords.some(keyword => msg.includes(keyword))) {
    const devicesData = await DeviceShadowManagerInstance.getSafeInfo()
    mymsg = "简要介绍一下我的车辆信息: " + DeviceShadowManagerInstance.summarizeDeviceStatus(devicesData)
  }
  const httpRequest = http.createHttp();

  // ========= 参数
  let url = 'https://api.siliconflow.cn/v1/chat/completions'
  const body = {
    model: "Qwen/Qwen2.5-Coder-7B-Instruct",
    messages: [{ role: "user", content: mymsg }]
  };
  const option: http.HttpRequestOptions = {
    method: http.RequestMethod.POST,
    header: {
      'Content-Type': 'application/json',
      'Accept': 'application/json', // ✅ 加上这一行更保险
      'Authorization': `Bearer sk-tpnmnzsqcizaohoznhwotqtgyklpirjxdvrgnugsicccbsqj`
    },
    extraData: JSON.stringify(body),
    readTimeout: 60000,
    connectTimeout: 60000,
  }

  // ========= 请求
  const response = await httpRequest.request(url, option);
  console.log(JSON.stringify(response.result))
  let result = JSON.parse(response.result as string) as ChatCompletion
  return result.choices[0].message.content
}